package com.example.elmspringboot.security.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.elmspringboot.domain.Business;
import com.example.elmspringboot.domain.User;
import com.example.elmspringboot.security.Jwt.JwtToken;
import com.example.elmspringboot.security.Jwt.JwtUtil;
import com.example.elmspringboot.service.BusinessService;
import com.example.elmspringboot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

@Slf4j
public class JwtShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private BusinessService businessService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 身份认证
     */
//    进行认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("-doGetAuthenticationInfo登录认证-");
        String tokenStr = (String) token.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(tokenStr);
        log.info("登录的用户:" + username);
        User user = userService.getUserByName(username);
        Business business = businessService.getOne(new QueryWrapper<Business>().eq("name", username));
        if (user!=null && JwtUtil.verify(tokenStr, username, user.getPassword())) {
            log.info("登录成功");
        }
        else if (business !=null && JwtUtil.verify(tokenStr, username, business.getPassword())) {
            log.info("登录成功");
        }
        else {
            throw new UnknownAccountException("用户名密码错误");
        }
        //数据库查出来的用户
        //验证密码是否正确

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(token.getCredentials(), token.getCredentials(), this.getName());
        return simpleAuthenticationInfo;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("执行doGetAuthorizationInfo方法进行授权");
        String username = JwtUtil.getUsername(principalCollection.toString());

        log.info("登录的用户:" + username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("role_admin");
        info.addStringPermission("user:add");
        info.addStringPermission("user:list");
        return info;
    }
}
